/**
	Alfresco Javascript Library
**/

/**
 * alfresco root namespace.
 */
if (typeof alfresco == "undefined" || !alfresco)
{
   var alfresco = {};
}

/**
 * alfresco top-level service namespace.
 */
alfresco.message = alfresco.message || {};

/**
 *  Utilities for handling alfresco ticket based authentication.
 */

alfresco.message = function() 
{
	var alfMessages = {
		"org.alfresco.blog.post-created":"{0} blog post created by {1}",
		"org.alfresco.blog.post-updated":"{0} blog post updated by {1}",
		"org.alfresco.blog.post-deleted":"{0} blog post deleted by {1}",
		"org.alfresco.comments.comment-created":"{1} commented on {0}",
		"org.alfresco.comments.comment-updated":"{1} updated comment on {0}",
		"org.alfresco.comments.comment-deleted":"{1} deleted a comment from {0}",
		"org.alfresco.discussions.post-created":"{0} discussion started by {1}",
		"org.alfresco.discussions.post-updated":"{0} discussion updated by {1}",
		"org.alfresco.discussions.post-deleted":"{0} discussion deleted by {1}",
		"org.alfresco.discussions.reply-created":"{1} replied to the discussion {0}",
		"org.alfresco.discussions.reply-updated":"{1} updated a reply to {0}",
		"org.alfresco.calendar.event-created":"{0} calendar event created by {1}",
		"org.alfresco.calendar.event-updated":"{0} calendar event updated by {1}",
		"org.alfresco.calendar.event-deleted":"{0} calendar event deleted by {1}",
		"org.alfresco.documentlibrary.file-added":"{0} document added by {1}",
		"org.alfresco.documentlibrary.files-added":"{0} documents added by {1}",
		"org.alfresco.documentlibrary.file-deleted":"{0} was deleted by {1}",
		"org.alfresco.documentlibrary.files-deleted":"{0} documents deleted by {1}",
		"org.alfresco.documentlibrary.file-updated":"{0} document updated by {1}",
		"org.alfresco.documentlibrary.files-updated":"{0} documents updated by {1}",
		"org.alfresco.wiki.page-created":"{0} wiki page created by {1}",
		"org.alfresco.wiki.page-edited":"{0} wiki page updated by {1}",
		"org.alfresco.wiki.page-renamed":"{2} wiki page renamed to {0} by {1}",
		"org.alfresco.wiki.page-deleted":"{0} wiki page deleted by {1}",
		"org.alfresco.site.group-added":"{1} group added to site {4} with role {2}",
		"org.alfresco.site.group-removed":"{1} group removed from site {4}",
		"org.alfresco.site.group-role-changed":"{1} group role changed to {2}",
		"org.alfresco.site.user-joined":"{1} joined site {4} with role {2}",
		"org.alfresco.site.user-left":"{1} left site {4}",
		"org.alfresco.site.user-role-changed":"{1} role changed to {2}",
		"org.alfresco.links.link-created":"{0} link created by {1}",
		"org.alfresco.links.link-updated":"{0} link updated by {1}",
		"org.alfresco.links.link-deleted":"{0} link deleted by {1}"		
	};
	
	return {
		
		getMessage: function(key) {
			return alfMessages[key];
		}
		
	}
} ();	
/**
 * alfresco top-level service namespace.
 */
alfresco.service = alfresco.service || {};

/**
 *  Utilities for handling alfresco ticket based authentication.
 */

alfresco.service = function() 
{

	// Alfresco endpoint e.g. http://localhost:8080/alfresco
	var alfrescoEndpoint;
	var userName;
	var password;
	var ticket;
	
	var alfrescoServiceEndpoint;
		
	return {

		init: function(endpoint,u,pwd) {
			alfrescoEndpoint = endpoint;
			alfrescoServiceEndpoint = alfrescoEndpoint+'/service';
			userName = u;
			password = pwd;
			alfresco.service.getActivities();
			//alfresco.service.loadFriendsActivities();
		},

		getTicket: function() {		
			return ticket;
		},
		
		getFullServiceUrl: function(url) {
			
			//Replace the userId placeholder
			if ( url.indexOf('{userId}') != -1  ) {
				url = url.replace('{userId}',userName);
			}
			if ( url.indexOf('?') != -1  ) {
				return alfrescoServiceEndpoint+url.replace('?','?alf_ticket='+ticket+'&');				
			} else {
				return alfrescoServiceEndpoint+url+'?alf_ticket='+ticket;
			}
		},
		
		getActivities: function() {

			//Invoke Alfresco login service to retreive ticket.
			var loginUrl = alfrescoServiceEndpoint+'/api/login?u='+userName+'&pw='+password+'&format=json';

			var params = {};
		    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;

			gadgets.io.makeRequest( loginUrl,function(result) {
  				if (result.error) {
  					alert('Failed to retreive Alfresco authentication ticket.');
  				} else {
  					//alert('Get ticket '+ result.data.data.ticket);
  					ticket =  result.data.data.ticket;
  					//document.getElementById("alf_server").innerHTML = this.ticket;
					//Prepare Alfresco activity service url.
					var activityServiceUrl = alfresco.service.getFullServiceUrl('/api/activities/feed/user?format=json&exclOthers=true');
					var params2 = {};
				    params2[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
					gadgets.io.makeRequest( activityServiceUrl,alfresco.service.processActivities,params2);
  				}
 			},params);
 
		},  

		processActivities : function(result) {
		

			var html = new Array();
			
			html.push('<div>');
						
			var feedData = result.data;
			
			for ( var i = 0 ; i < feedData.length ; i++ ) {
				
				var feedSummary = eval( '('+feedData[i].activitySummary+')' );
				
				html.push('<div>', feedData[i].siteNetwork,' ',feedData[i].activityType,' ',feedSummary.title, ' ', feedData[i].postDate, '</div>');
			
			}
			
			html.push('</div>');
			
			document.getElementById('my_activities').innerHTML = html.join('');

			var json = gadgets.json.stringify(result.data);
			var req = opensocial.newDataRequest();
  			req.add(req.newUpdatePersonAppDataRequest("VIEWER", 'myactivities', json));
  			req.send(alfresco.service.loadFriendsActivities);

		},
		
        loadFriendsActivities : function() {
        
          var req = opensocial.newDataRequest();
          req.add(req.newFetchPersonRequest("VIEWER"), 'viewer');
					
		  var viewerFriends = opensocial.newIdSpec({ "userId" : "VIEWER", "groupId" : "FRIENDS" });
		  var opt_params = {};
		  opt_params[opensocial.DataRequest.PeopleRequestFields.MAX] = 100;
          req.add(req.newFetchPeopleRequest(viewerFriends, opt_params), 'viewerFriends');

          var viewer = opensocial.newIdSpec({ "userId" : "VIEWER" });
          req.add(req.newFetchPersonAppDataRequest(viewer, 'myactivities'), 'data');

          req.add(req.newFetchPersonAppDataRequest(viewerFriends, 'myactivities', opt_params), 'viewerFriendData');
          req.send(alfresco.service.onLoadFriendsActivities);
        },
        
        onLoadFriendsActivities : function (data) {
        
        	var viewer = data.get('viewer').getData();
			var viewerFriends = data.get('viewerFriends').getData();
			var activityData = data.get('data').getData();
			var viewerFriendData = data.get('viewerFriendData').getData();
			
			var html = new Array();			
			html.push('<div>');
			
			viewerFriends.each(function(person) {
			
				var jsonStr = viewerFriendData[person.getId()]['myactivities'];
							
				var json = gadgets.json.parse(gadgets.util.unescapeString(jsonStr));
				
				for ( var j = 0 ; j < json.length ; j++ ) {

					var feedSummary = eval( '('+json[j].activitySummary+')' );

					var postDate = new Date();
					
					gadgets.i18n.parseDateTime("yyyy-MM-ddThh:mm:ss.000Z", json[j].postDate, 0, postDate); 
					
					var postDateStr = gadgets.i18n.formatDateTime("MM/dd/yyyy hh:mm:ss", postDate);
					
					html.push('<div>', json[j].siteNetwork,' ',alfresco.message.getMessage(json[j].activityType),' ',feedSummary.title, '@', postDateStr, '</div>');

				}
			});
						
			html.push('</div>');
			
			document.getElementById('friends_activities').innerHTML = html.join('');
			
			//gadgets.window.adjustHeight();			
        
        }
		
				
	}	

} ();

